import 'package:bt_dsp_88/model/model_send.dart';
import 'package:flutter/material.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

import '../../class/dialog/password_input.dart';
import '../../commont/button.dart';
import '../../main.dart';
import '../../model/model.dart';
import '../../model/model_default.dart';
import '../../model/model_extension.dart';
import '../../tool/assets.dart';
import '../../tool/tool.dart';

class SaveView extends BaseDialog {
  SaveView({super.key});

  @override
  BaseDialogState createState() => _SaveViewState();
}

class _SaveViewState extends BaseDialogState<SaveView> with TickerProviderStateMixin {
  List<GlobalModel> _global_list = [];
  List<AnimationController> _controllers = [];
  List<Animation<Offset>> _offsetAnimations = [];
  String editKey = 'editKey';
  String localPassword = '';
  String currentPassword = '';
  String select_tag = '';
  @override
  void initState() {
    super.initState();
    loadLocal();
  }

  @override
  void dispose() {
    // 销毁所有的 AnimationController
    for (var controller in _controllers) {
      controller.dispose();
    }
    super.dispose();
  }

  ///加载本地数据
  Future<void> loadLocal() async {
    localPassword = await loadString(editKey);
    _global_list = await globalManager.getAll();

    // 为每一行创建单独的 AnimationController 和 Animation<Offset>
    _controllers = List.generate(_global_list.length, (index) {
      return AnimationController(
        duration: const Duration(milliseconds: 300),
        vsync: this,
      );
    });

    _offsetAnimations = List.generate(_global_list.length, (index) {
      return Tween<Offset>(begin: Offset.zero, end: const Offset(-0.2, 0)).animate(_controllers[index]);
    });

    setState(() {});
  }

  ///保存
  Future<void> save(String tag, String password) async {
    DateTime now = DateTime.now();
    String formattedDate = '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')} '
        '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}';

    var copy = globalModel.copy;
    copy.tag = tag;
    copy.date = formattedDate;
    copy.isLock = password.isNotEmpty;
    copy.getData();
    globalManager.update(copy);
    loadLocal();
    EasyLoading.showSuccess('Saved Successfully');
  }

  ///加载指定数据
  Future<void> load(String tag) async {
    if (select_tag == tag) {
      return;
    }
    setState(() {
      select_tag = tag;
    });

    GlobalModel model = _global_list.firstWhere(($0) => $0.tag == tag);
    globalModel.tag = model.tag;
    globalModel.mute = model.mute;
    globalModel.db = model.db;
    globalModel.date = model.date;
    globalModel.input_type = model.input_type;
    globalModel.copy_stype = model.copy_stype;
    globalModel.ch_list.removeRange(0, 8);
    globalModel.ch_list.addAll(model.ch_list.map(($0) => $0.copy).toList());
    globalModel.getData();
    globalModel.sendToDevice(tag: 'UPDATE');
  }

  Future<void> delete(String tag) async {
    var delete_model = _global_list.firstWhere(($0) => $0.tag == tag, orElse: () => globalModel);
    globalManager.deleteByPrimaryKey(delete_model.tag);
    loadLocal();
    EasyLoading.showSuccess('Deleted Successfully');
  }

  ///自定义删除按钮
  Widget _get_DeleteBtn({required Widget child, required int index, required void Function() onDelecte}) {
    return GestureDetector(
      onHorizontalDragUpdate: (details) {
        if (details.primaryDelta! < -10) {
          // 向左滑动超过阈值，触发该行的动画
          setState(() {
            print('=================>  向左滑动');
            _controllers[index].forward();
          });
        } else if (details.primaryDelta! > 10) {
          // 向右滑动超过阈值，恢复该行原状
          setState(() {
            print('=================>  向右滑动');

            _controllers[index].reverse();
          });
        }
      },
      child: Stack(
        children: [
          // 背景部分，例如删除按钮
          Positioned.fill(
            child: Container(
              color: Colors.red,
              alignment: Alignment.centerRight,
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: InkWell(
                onTap: onDelecte,
                child: const Icon(Icons.delete_forever, color: Color(0xFF808080)),
              ),
            ),
          ),
          // 可滑动的内容
          SlideTransition(
            position: _offsetAnimations[index],
            child: Container(
              color: select_tag == _global_list[index].tag ? Color_theme : Colors.white,
              child: child,
            ),
          ),
        ],
      ),
    );
  }

  void _showAlert(int tag, {Function()? completion = null}) {
    switch (tag) {
      ///直接 设置名字，存储
      case 1:
        PasswordInput password = PasswordInput(
          title: 'New Settings',
          style: PasswordInputStyle.setting,
          onOK: (p0) {
            save(p0, currentPassword);
          },
        );
        password.show(context);

      ///没有设置过密码，先设置密码
      case 2:
        PasswordInput password = PasswordInput(
          title: 'Please set new password',
          style: PasswordInputStyle.setNew,
          prefs_key: editKey,
          onOK: (p0) {
            localPassword = p0;
            currentPassword = p0;
            saveString(editKey, p0);
            _showAlert(1);
          },
        );
        password.show(context);

      ///设置过密码，先验证密码
      case 3:
        PasswordInput password = PasswordInput(
          title: 'Please enter your password',
          style: PasswordInputStyle.enterOld,
          prefs_key: editKey,
          password: localPassword,
          onOK: (p0) {
            if (localPassword != p0) {
              localPassword = p0;
              saveString(editKey, p0);
            }
            currentPassword = p0;
            if (completion != null) {
              completion();
            } else {
              _showAlert(1);
            }
          },
        );
        password.show(context);
        break;
      default:
    }
  }

  ///本地数据列表
  Widget _get_list(double width, double height) {
    return GridView.extent(
        maxCrossAxisExtent: width,
        crossAxisSpacing: 0,
        mainAxisSpacing: 0,
        childAspectRatio: width / 40,
        children: _global_list.asMap().entries.map(($0) {
          return Container(
            width: width,
            height: 40,
            child: _get_DeleteBtn(
              index: $0.key,
              child: InkWell(
                ///加载本地数据
                onTap: () {
                  if ($0.value.isLock) {
                    _showAlert(3, completion: () {
                      load($0.value.tag);
                    });
                  } else {
                    load($0.value.tag);
                  }
                },
                child: Stack(
                  children: [
                    Positioned(
                      left: 10,
                      top: 0,
                      bottom: 0,
                      child: Center(
                        child:
                            Image.asset(assets.lock, width: $0.value.isLock ? 16 : 0, height: $0.value.isLock ? 16 : 0),
                      ),
                    ),

                    ///名字
                    Positioned(
                      left: $0.value.isLock ? 30 : 20,
                      right: 50,
                      top: 4,
                      height: 20,
                      child: Text(
                        $0.value.tag,
                        style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: Colors.black),
                      ),
                    ),

                    ///时间
                    Positioned(
                      left: $0.value.isLock ? 32 : 22,
                      right: 50,
                      top: 20,
                      height: 20,
                      child: Text(
                        $0.value.date,
                        style: const TextStyle(fontSize: 12, color: Colors.grey),
                      ),
                    ),

                    ///分享
                    Positioned(
                      right: 10,
                      top: 0,
                      height: 40,
                      width: 40,
                      child: imgButton(
                          img: Image.asset(assets.share, width: 20, height: 20),
                          groundColor: Colors.transparent,
                          overColor: Colors.transparent,
                          shadowRadius: 0,
                          // 触发分享功能
                          onClick: () {
                            if ($0.value.isLock) {
                              _showAlert(3, completion: () {
                                share($0.value);
                              });
                            } else {
                              share($0.value);
                            }
                          }),
                    ),

                    ///下划线
                    Positioned(left: 0, right: 0, bottom: 0, child: Container(height: 0.5, color: Colors.black))
                  ],
                ),
              ),

              ///删除方法
              onDelecte: () {
                if ($0.value.isLock) {
                  _showAlert(3, completion: () {
                    delete($0.value.tag);
                  });
                } else {
                  delete($0.value.tag);
                }
              },
            ),
          );
        }).toList());
  }

  ///头部按钮
  Widget _get_header_item(double width, double height, String text) {
    return SizedBox(
      width: width,
      height: height,
      child: TextButton.icon(
        onPressed: () {
          if (text == 'Basic Tuning Presets') {
            currentPassword = '';
            _showAlert(1);
          } else if (text == 'Adavnced Tuning Presets') {
            _showAlert(currentPassword.isNotEmpty
                ? 1
                : localPassword == ''
                    ? 2
                    : 3);
          }
        },
        icon: Image.asset(assets.new_save, width: 20),
        label: Text(
          text,
          textAlign: TextAlign.center,
          style: const TextStyle(fontSize: 14, color: Colors.black, height: 0),
        ),
        style: ButtonStyle(
          padding: const WidgetStatePropertyAll(EdgeInsets.only(left: 5, right: 5)),
          overlayColor: WidgetStatePropertyAll(Color_bg_view.withOpacity(0.4)),
          shadowColor: WidgetStatePropertyAll(Color_bg_view.withOpacity(0.4)),
          shape: const WidgetStatePropertyAll(RoundedRectangleBorder(borderRadius: BorderRadius.zero)),
        ),
      ),
    );
  }

  ///头部
  Widget _get_header(double width, double height) {
    return SizedBox(
        height: height,
        child: Column(
          children: [
            Expanded(
                child: Row(
              children: [
                _get_header_item((width - 1) / 2.0, height, 'Basic Tuning Presets'),
                Container(width: 1, color: Colors.black),
                _get_header_item((width - 1) / 2.0, height, 'Adavnced Tuning Presets'),
              ],
            )),
            Container(height: 1, color: Colors.black)
          ],
        ));
  }

  @override
  Widget buildContent(BuildContext context) {
    return LayoutBuilder(builder: (BuildContext context, BoxConstraints constrains) {
      return Container(
        height: 520,
        child: Column(
          children: [
            Container(
              color: Colors.transparent,
              child: _get_header(constrains.maxWidth, 50),
            ),
            Expanded(child: _get_list(constrains.maxWidth, 520 - 50)),
          ],
        ),
      );
    });
  }
}
